package io.xxx.xbutler.domain.task;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.Fastjson2TypeHandler;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.xxx.xbutler.core.check.CheckError;
import lombok.Data;
import org.apache.ibatis.type.EnumTypeHandler;

import java.time.LocalDateTime;

@Data
@TableName(autoResultMap = true)
public class TaskItem {

    @TableId
    private Long id;

    private Long taskId;

    /**
     * 从0开始，消息组内序号
     */
    private Integer sn;

    /**
     * 从0开始，消息组序号
     */
    private Integer psn;

    @TableField(typeHandler = EnumTypeHandler.class)
    private MessageType messageType;

    @TableField(typeHandler = EnumTypeHandler.class)
    private ContentType contentType;

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONObject content;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdTime;

    /**
     * 经过检查后，如果有错误需要进行标记
     */
    @TableField(exist = false)
    private Integer errorCode;

    @TableField(exist = false)
    private String errorMessage;

    public boolean isMiniProgram() {
        return messageType == MessageType.MINI_PROGRAM;
    }

    public boolean isProduct() {
        return assign(MessageType.MINI_PROGRAM, ContentType.PRODUCT);
    }

    public boolean isFavoriteProduct() {
        return assign(MessageType.MINI_PROGRAM, ContentType.FAVORITE_PRODUCT);
    }

    public boolean isVenue() {
        return assign(MessageType.MINI_PROGRAM, ContentType.VENUE);
    }

    public boolean assign(MessageType messageType, ContentType contentType) {
        if (contentType == null) {
            return false;
        }
        return messageType == this.messageType && contentType == this.contentType;
    }

    public void setError(CheckError error) {
        this.errorCode = error.getErrorCode();
        this.errorMessage = error.getErrorMessage();
    }
}
